<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.controller' );

class EcommerceController extends JController
{
	function display()
	{
		parent::display();
	}
	
	function addCart(){
		$db = &JFactory::getDBO();
		$user = & JFactory::getUser();
		$session =& JFactory::getSession();
	
		$id = intval( JRequest::getVar('id') );
		$quantity = intval( JRequest::getVar('quantity') );
		
		if($id){
			$kt=0;
		
			for($i=1; $i<=intval($session->get('itemAmount')); $i ++ ){
				if($id == intval($session->get('id'.$i))){
					$kt=1;
					break;
				}
			}
			if($kt == 0){
				$query = "select * from #__pr_product where id = ". $id;
				$db->setQuery($query);
				$row = $db->loadObject();
				
				$itemAmount = intval($session->get('itemAmount'));
				$itemAmount = $itemAmount + 1 ;
				$session->set('itemAmount', $itemAmount);
		
				$i = intval($session->get('itemAmount'));
				$session->set('id'.$i, $row->id);
				$session->set('name'.$i, $row->name);
				$session->set('price'.$i, $row->price);
				$session->set('quantity'.$i, $quantity);
				
				$query = "INSERT INTO #__pr_session_cart(user_id, product_id, product_name, product_price, product_quantity) VALUES (".$user->id.", ".$row->id.", '".$row->name."', ".$row->price.", ".$quantity.")";
				$db->setQuery($query);
				$db->query();
			} else {
				$quantity1 = $session->get('quantity'.$i) + $quantity;
				$session->set('quantity'.$i, $quantity1);
				
				$query = "UPDATE #__pr_session_cart SET product_quantity = ".$quantity1." WHERE product_id = ".$id." AND user_id = ".$user->id;
				$db->setQuery($query);
				$db->query();
			}
			
			echo 1;
			exit;
		}
		echo 0;
		exit;
	}
	
	function addOrderCart(){
		$db = &JFactory::getDBO();
		$user = & JFactory::getUser();
		$session =& JFactory::getSession();
	
		$arrId = JRequest::getVar('id');
		$arrQuantity = JRequest::getVar('quantity');
		
		for($y = 0; $y<count($arrId); $y++){
			$kt=0;
		
			for($i=1; $i<=intval($session->get('itemAmount')); $i ++ ){
				if($arrId[$y] == intval($session->get('id'.$i))){
					$kt=1;
					break;
				}
			}
			if($kt == 0){
				$query = "SELECT * FROM #__pr_product where id = ". $arrId[$y];
				$db->setQuery($query);
				$row = $db->loadObject();
				
				$itemAmount = intval($session->get('itemAmount'));
				$itemAmount = $itemAmount + 1 ;
				$session->set('itemAmount', $itemAmount);
		
				$i = intval($session->get('itemAmount'));
				$session->set('id'.$i, $row->id);
				$session->set('name'.$i, $row->name);
				$session->set('price'.$i, $row->price);
				$session->set('quantity'.$i, $arrQuantity[$y]);
				
				$query = "INSERT INTO #__pr_session_cart(user_id, product_id, product_name, product_price, product_quantity) VALUES (".$user->id.", ".$row->id.", '".$row->name."', ".$row->price.", ".$arrQuantity[$y].")";
				$db->setQuery($query);
				$db->query();
			} else {
				$quantity = $session->get('quantity'.$i) + $arrQuantity[$y];
				$session->set('quantity'.$i, $quantity);
				
				$query = "UPDATE #__pr_session_cart SET product_quantity = ".$quantity." WHERE product_id = ".$id." AND user_id = ".$user->id;
				$db->setQuery($query);
				$db->query();
			}
		}
		echo 1;
		exit;
	}
	
	function loadCart(){
		$db = &JFactory::getDBO();
		$session =& JFactory::getSession();
		$html = "";
		for($i = 1; $i <= $session->get('itemAmount'); $i++){
			$query = "select id, name, price FROM #__pr_product WHERE id = ".$session->get('id'.$i);
			$db->setQuery($query);
			$item = $db->loadObject();
			$html .= '<div class="eachCart">                        		
                    <p class="eachCart-name">'.$session->get('name'.$i).'</p>
					<input type="hidden" id="idRemove'.$session->get('id'.$i).'" name="idRemove'.$session->get('id'.$i).'" value="'.$session->get('id'.$i).'" />
                    <a class="eachClose" href="javascript:void(0);"></a>
                    <div class="eachCart-box clear-fix">
                        <p class="eachCart-value">Pris: '.$session->get('price'.$i).' kr</p>
                        <div class="eachCart-quantity clear-fix">
                            <a class="btnDown">Down</a>
                            <input class="inputSoluong" type="text" value="'.$session->get('quantity'.$i).'" />
                            <a class="btnUp">Up</a>
							<input type="hidden" value="'.$session->get('id'.$i).'" />
							<a class="btnRefresh">Refresh</a>
                        </div>
                    </div>                        		
                </div>';
		}
		echo $html;
		exit;
	}
	
	function loadLittleCart(){
		$db = &JFactory::getDBO();
		$session =& JFactory::getSession();
		
		$moneyTotal = 0;
		for($i = 1; $i <= $session->get('itemAmount'); $i++){
			$moneyToTal += ($session->get('price'.$i)*$session->get('quantity'.$i));
		}
		if($session->get('itemAmount')) $itemAmount = $session->get('itemAmount'); 
		else $itemAmount = 0;
		
		$html = "<p>Antal varer: ".$itemAmount."</p>
            <p>Total beløb: ".number_format($moneyToTal,0,',','.')." DKK</p>";
			
		echo $html;
		exit;
	}
	
	function deleteItem(){
		$session =& JFactory::getSession();
	
		for ($i= intval(JRequest::getVar('i')); $i< intval($session->get('itemAmount')); $i++){
			$j = $i + 1;
			$session->set('id'.$i, $session->get('id'.$j));
			$session->set('name'.$i, $session->get('name'.$j));
			$session->set('quantity'.$i, $session->get('quantity'.$j));
			$session->set('price'.$i, $session->get('price'.$j));
		}
		$current_tongsl = intval($session->get('itemAmount')) - 1;
		$session->set('itemAmount', $current_tongsl);
	
		echo 1;
		exit;
	}
	
	function updateCart(){
		$session =& JFactory::getSession();
		$id = intval( JRequest::getVar('id') );
		$quantity = intval( JRequest::getVar('quantity') );
		for ($i=1; $i<=intval($session->get('itemAmount')); $i++){
			if($session->get('id'.$i) == $id){
				$session->set('quantity'.$i , $quantity);
			}
		}
		echo 1;
		exit;
	}
	
	function checkOut(){
		$db		= &JFactory::getDBO();
		$user = & JFactory::getUser();
		$session =& JFactory::getSession();
		$comment = JRequest::getVar('comment');
		
		$query = "INSERT INTO #__pr_orders (order_date, order_user_id, order_status, order_comment) value('".time()."' ,".$user->id.", 0, '".$comment."')";
		$db->setQuery($query);
		$db->query();
		$order_id = $db->insertid();
		
		$order_total=0;
		for($i=1 ; $i<= $session->get('itemAmount'); $i ++)
		{
			$product_id = $session->get('id'.$i) ;
			$product_name = $session->get('name'.$i) ;
			$quantity =  $session->get('quantity'.$i) ;
			$price = $session->get('price'.$i) ;
			$total = $price*$quantity ;
			$order_total += $total;
			$query_customer = "INSERT INTO #__pr_cart(order_id, product_id, product_name, quantity ,  price , total ) VALUE ($order_id, $product_id, '$product_name', $quantity, $price, $total)";
			
			$db->setQuery($query_customer);
			$db->query();
		}
		$query = "UPDATE #__pr_orders SET order_total = $order_total WHERE order_id = $order_id ";
		$db->setQuery($query);
		$db->query();
		
		$db->setQuery("SELECT email FROM #__users WHERE id = 62");
		$admin_email = $db->loadResult();
		
		if($this->sendEmail($order_id, $user->email, $admin_email)){
			$session->set("itemAmount", 0);
			$query = "DELETE FROM #__pr_session_cart WHERE user_id = ".$user->id;
			$db->setQuery($query);
			$db->query();
			$this->setRedirect("index.php?option=com_ecommerce&view=overall&layout=success&Itemid=16");
		} else {
			$this->setRedirect("index.php?option=com_ecommerce&view=list&Itemid=16",'Kan ikke sende mails');
		}
	}
	
	function sendMyEmail(){
		$user = & JFactory::getUser();
		$order_id = JRequest::getVar('order_id');
		if($this->sendEmail($order_id, $user->email)){
			$this->setRedirect("index.php?option=com_ecommerce&view=overall&Itemid=18",'Ordrer er blevet sendt til din e-mail');
		} else {
			$this->setRedirect("index.php?option=com_ecommerce&view=list&Itemid=16",'Kan ikke sende mails');
		}
	}
	
	function sendEmail($order_id, $to, $cc = ''){
		$db		= &JFactory::getDBO();
		$user = & JFactory::getUser();
		
		$query = "SELECT * FROM #__users_extension WHERE id = ".$user->id;
		$db->setQuery($query);
		$user_info = $db->loadObject();
		
		$mail = new JConfig();
		$from = $mail->mailfrom;

		$subject = $mail->fromname.' - Bekendtgørelse nr. '.sprintf("%10d", $order_id).' af '.$user->name;
		
		$query = "SELECT order_date, order_comment FROM #__pr_orders WHERE order_id = ".$order_id;
		$db->setQuery($query);
		$order_info = $db->loadObject();
		$order_text = sprintf("%06d", $order_id);
		$body = '
			<body style="font-family: \'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif; ">

<table style="width:780px; margin:0px auto; padding:10px;" width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><a style=" background:url('.JURI::base().'templates/cafe_shop/src/images/imgLogo.png) no-repeat; text-indent:-9999px; width:180px; height:93px; display:block; ">Danskcafe</a></td>
  </tr>
  <tr>
  	<td colspan="1">
    	<table width="780px" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td style="background-color:#ea1d2b; padding:1px; color:white; font-size:15px; font-weight:bold;" colspan="2" >Faktura</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px;" width="313">Faktura nummer:</td>
            <td width="467" style="color:#323232; font-size:12px; padding:1px;">'.$order_text.'</td>
          </tr>
		  <tr>
            <td style="color:#323232; font-size:12px; padding:1px;" width="313">Faktura dato:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.date('d-m-Y', $order_info->order_date).'</td>
          </tr>
		   <tr>
            <td style="color:#323232; font-size:12px; padding:1px;" width="313">Tidspunkt:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.date('H:i:s', $order_info->order_date).'</td>
          </tr>
          <tr>
            <td style="background-color:#ea1d2b; padding:1px; color:white; font-size:15px; font-weight:bold;" colspan="2" >Kundeinformation</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Firma/institution:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->company.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Kontaktperson:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user->name.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Adresse:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->address.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Postnr.:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->post.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">By:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->city.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Telefon/mobil:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->phone.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">CVR-nr.:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user_info->cvr.'</td>
          </tr>
          <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">E-mail:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$user->email.'</td>
          </tr>
		  <tr>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">Kommentar:</td>
            <td style="color:#323232; font-size:12px; padding:1px; width:30%; ">'.$order_info->order_comment.'</td>
          </tr>		 
       </table>
    </td>
  </tr>
  <tr>
  	<td style="border-bottom: 1px solid #ea1d2b;">
  		<table width="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
	            <td style="background-color:#ea1d2b; padding:1px; color:white; font-size:15px; font-weight:bold;" colspan="8" >Ordrelinier</td>
	        </tr>
			<tr>
		       	<td width="85" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Varenr</td>
		       	<td width="241" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Varenavn</td>
		       	<td width="125" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Pris/enhed</td>
                <td width="117" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Antal</td>
                <td width="212" style="color:#323232; font-size:11px; text-align:center; padding:1px; ">Subtotal</td>
                		    
		    </tr>
			';
			$db->setQuery("SELECT order_total FROM #__pr_orders WHERE order_id = ".$order_id);
			$order_total = $db->loadResult();
			
			$query = "SELECT * FROM #__pr_cart WHERE order_id = ".$order_id;
			$query = $db->setQuery($query);
			$cart = $db->loadObjectList();
						
			foreach ($cart as $item) {
				$query = "SELECT number FROM #__pr_product WHERE id = ".$item->product_id;
				$query = $db->setQuery($query);
				$pro = $db->loadObject();
		    $body .= '
			<tr>
		       	<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$pro->number.'</td>
		       	<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->product_name.'</td>
		       	<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->price.' kr</td>
				<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->quantity.'</td>
				<td style="color:#323232; font-size:11px; text-align:center; padding:1px; ">'.$item->price*$item->quantity.' kr</td>
		    </tr>';
			}
            $body .= '    
        </table>
  	</td>
  </tr>
  <tr>
  	<td style="text-align: right; color:#323232; font-size:12px; padding:0px; padding:2px 43px 50px 0; font-weight: bold;">At betale: '.$order_total.' kr</td>
  </tr>
  <tr>
  	<td style="background-color:#ea1d2b; padding:1px; ">
  		<p style="color:#FFF; font-size:13px; margin:0;">Dansk Cafe Service - Vesterbrogade 74,3. sal - 1620 København V - Tlf: +45 26 80 88 11</p> 
  		<p style="color:#FFF; font-size:13px; margin:0;">Mail: <a onmouseover="this.style.textDecoration = \'underline\'" onmouseout="this.style.textDecoration = \'none\'" style="display:inline; text-decoration: none; color:#FFF;" href="mailto:post@danskcafeservice.dk">post@danskcafeservice.dk</a> - CVR: 30892968</p>
  	
	</td>
  </tr>
</table>
</body>
		';
		
		$message =& JFactory::getMailer();
		$message->IsHTML(true);
		$message->addRecipient($to);
		if($cc){
			$message->addCC($cc);
		}
		$message->setSubject($subject);
		$message->setBody($body);
		$sender = array( $from, $mail->sitename );
		$message->setSender($sender);
		$sent = $message->send();
		if($sent){
			return true;
		} else {
			return false;
		}
	}
	
	
	function exportPdf(){
		
		require_once("libraries/joomla/document/pdf/pdf.php");
		$db		= &JFactory::getDBO();
		$user = & JFactory::getUser();
		
		$order_id = JRequest::getVar('order_id');
		
		$query = "SELECT * FROM #__users_extension WHERE id = ".$user->id;
		$db->setQuery($query);
		$user_info = $db->loadObject();
		
		$query = "SELECT order_date, order_comment FROM #__pr_orders WHERE order_id = ".$order_id;
		$db->setQuery($query);
		$order_info = $db->loadObject();
		$order_text = sprintf("%06d", $order_id);
		$body = '
			<table width="650" border="0" cellspacing="0" cellpadding="0">
			  <tr>
				<td><a href="index.php"><img src="images/imgLogo.jpg" width="150" /></a></td>
			  </tr>
			</table>
			<table width="650" border="0" cellspacing="0" cellpadding="0">
			  <tr>
				<td colspan="2" style="background-color:#ea1d2b; color:white;"><b>Faktura</b></td>
			  </tr>
			  <tr>
				<td width="309">Faktura nummer:</td>
				<td width="341">'.$order_text.'</td>
			  </tr>
			  <tr>
				<td width="309">Faktura dato:</td>
				<td width="341">'.date('d-m-Y', $order_info->order_date).'</td>
			  </tr>
			  <tr>
				<td width="309">Tidspunkt:</td>
				<td width="341">'.date('H:i:s', $order_info->order_date).'</td>
			  </tr>
			  <tr>
				<td colspan="2" >&nbsp;</td>
			  </tr>
			  <tr>
				<td colspan="2" style="background-color:#ea1d2b; color:white;"><b>Kundeinformation</b></td>
			  </tr>
			  <tr>
				<td width="309">Firma/institution:</td>
				<td width="341">'.$user_info->company.'</td>
			  </tr>
			  <tr>
				<td width="309">Kontaktperson:</td>
				<td width="341">'.$user->name.'</td>
			  </tr>
			  <tr>
				<td width="309">Adresse:</td>
				<td width="341">'.$user_info->address.'</td>
			  </tr>
			  <tr>
				<td width="309">Postnr.:</td>
				<td width="341">'.$user_info->post.'</td>
			  </tr>
			  <tr>
				<td width="309">By:</td>
				<td width="341">'.$user_info->city.'</td>
			  </tr>
			  <tr>
				<td width="309">Telefon/mobil:</td>
				<td width="341">'.$user_info->phone.'</td>
			  </tr>
			  <tr>
				<td width="309">CVR-nr.:</td>
				<td width="341">'.$user_info->cvr.'</td>
			  </tr>
			  <tr>
				<td width="309">E-mail:</td>
				<td width="341">'.$user->email.'</td>
			  </tr>
			</table>
			<table width="650" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td>&nbsp;</td>
				  </tr>
				<tr>
					<td style="background-color:#ea1d2b; color:white;" width="650"><b>Ordrelinier</b></td>
				</tr>
			</table>
			<table width="650" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td width="100">Varenr</td>
					<td width="250">Varenavn</td>
					<td width="100">Pris/enhed</td>
					<td width="80">Antal</td>
					<td width="120">Subtotal</td>
				</tr>
				<tr><td colspan="5">&nbsp;</td></tr>
			';
			$db->setQuery("SELECT order_total FROM #__pr_orders WHERE order_id = ".$order_id);
			$order_total = $db->loadResult();
			
			$query = "SELECT * FROM #__pr_cart WHERE order_id = ".$order_id;
			$query = $db->setQuery($query);
			$cart = $db->loadObjectList();
						
			foreach ($cart as $item) {
				$query = "SELECT number FROM #__pr_product WHERE id = ".$item->product_id;
				$query = $db->setQuery($query);
				$pro = $db->loadObject();
		    $body .= '
			<tr>
				<td width="100" >'.$pro->number.'</td>
				<td width="250" >'.$item->product_name.'</td>
				<td width="100" >'.$item->price.' kr</td>
				<td width="80" >'.$item->quantity.'</td>
				<td width="120" >'.$item->price*$item->quantity.' kr</td>
			</tr>
			';
			}
            $body .= '
			<tr><td colspan="5" width="650"><hr></td></tr>
			</table>   
			<table width="650" border="0" cellspacing="0" cellpadding="0">
			  <tr>
			  	<td width="650" style="text-align: right; color:#323232; font-size:12px; padding:0px; padding:2px 0px 20px 0; font-weight: bold;"><b>At betale: '.$order_total.' kr &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>
			  </tr>
			  <tr>
				<td style="color:white; width:650px; background-color:#ea1d2b">Dansk Cafe Service - Vesterbrogade 74,3. sal - 1620 København V - Tlf: +45 26 80 88 11<br />Mail: post@danskcafeservice.dk - CVR: 30892968
				</td>
			  </tr>
			</table>
		';
		//$body = '<page style="font-family: freeserif"><br />'.nl2br($body).'</page>';
		require("html2pdf/html2pdf.class.php");
		$name = 'Faktura nr. '.$order_id.' '.date("d-m-Y");
		$file_name = $name.".pdf";
		$encoded_filename = urlencode($file_name);
		$encoded_filename = str_replace("+", "%20", $encoded_filename);
		$ua = $_SERVER["HTTP_USER_AGENT"];
		$pdf = new HTML2PDF('P', 'A4', 'da');
		$pdf->pdf->SetDisplayMode('real');
		//$pdf->SetFont('arial','',5);//print_r($pdf);exit;
		$pdf->WriteHTML($body);
		$pdf->Output('images/pdf/'.$name.'.pdf', 'F'); 
			
		$url = "/var/www/clients/client22/web140/web/images/pdf/".$file_name;
		//$url = "D:/xampp/htdocs/cafe/images/pdf/".$file_name;
		$handle = fopen($url, "r");
		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		
		//header('Content-Disposition: attachment; filename='.$encoded_filename);
		if (preg_match("/MSIE/", $ua)) {
			header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
		} else if (preg_match("/Firefox/", $ua)) {
			header('Content-Disposition: attachment; filename*="' . $file_name . '"');
		} else {
			header('Content-Disposition: attachment; filename="' . $file_name . '"');
		}
			
		header('Content-Transfer-Encoding: binary');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		header('Content-Length: ' . filesize($url));
		ob_clean();
		flush();
		readfile($url);
		fclose($handle);
		exit;
	}
}
?>